package com.budwk.app.gzsocket.wsclient;


import com.budwk.starter.common.constant.RedisConstant;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.transports.WebSocket;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;

import java.net.URI;
import java.util.UUID;

@IocBean
public class ChatSocketClient {
    @Inject
    RedisService redisService;
    @Inject
    private PropertiesProxy conf;

    private Socket socket;

    public void start()  {
        URI uri = URI.create(conf.get("chatsocket.wsurl"));
        IO.Options options = new IO.Options();
        options.path = conf.get("chatsocket.content");
        options.transports = new String[]{WebSocket.NAME};
        String key = UUID.randomUUID().toString();
        String value = UUID.randomUUID().toString();
        redisService.set(RedisConstant.GLOBALS_DATA+"adminkey:"+key,value);
        redisService.expire(RedisConstant.GLOBALS_DATA+"adminkey:"+key,3600);
        options.query = "adminkey="+key+"&adminvalue="+value;
        socket = IO.socket(uri,options);
        socket.open();

        socket.on("message", new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                Object chatObject = objects[0];
                System.out.println("接收到服务器回传的消息"+chatObject.toString());
            }
        });
        //查询用户可以加入的房间信息，包括用户room，群组room
        socket.on("queryUserRooms", new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                //传递的接口为token
                Object chatObject = objects[0];

                System.out.println("服务器端查询用户群组消息 ： "+chatObject.toString());
            }
        });

        System.out.println("客户端认证请求结束 : 连接状态 "+socket.connected());

    }

    /**
     * 发送消息
     * @param channle 消息类型，
     * @param event 消息事件
     * @param data 消息体
     */
    public void sendMessage(String channle,String event,Object data){
        ChatWsMessage chatWsMessage = new ChatWsMessage();
        chatWsMessage.setChannel(channle);
        chatWsMessage.setEvent(event);
        chatWsMessage.setData(data);
        socket.emit("message", Json.toJson(chatWsMessage));
    }
}
